package com.flyduck.security.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.text.MessageFormat;

/**
 * <p></p>
 *
 * @author flyduck 2021/7/5
 * @version V1.0
 * @modificationHistory=========================逻辑或功能性重大变更记录
 * @modify by user: flyduck 2021/7/5
 * @modify by reason:{方法名}:{原因}
 **/
@Component
public class MD5PasswordEncoder implements PasswordEncoder {

    private static final Logger LOGGER = LoggerFactory.getLogger(MD5PasswordEncoder.class);

    private static final String ALGORITHM = "MD5";

    @Override
    public String encode(CharSequence charSequence) {
        return md5Crypt(charSequence);
    }

    @Override
    public boolean matches(CharSequence charSequence, String s) {
        return s.equals(md5Crypt(charSequence));
    }

    private String md5Crypt(CharSequence charSequence)
    {
        try
        {
            MessageDigest md5 = MessageDigest.getInstance(ALGORITHM);
            md5.update(charSequence.toString().getBytes());
            return new BigInteger(1, md5.digest()).toString(16);
        }
        catch (Exception e)
        {
            LOGGER.error(MessageFormat.format("MD5 crypt failed, message: {0}", e.getMessage()));
        }
        return null;
    }
}
